import { Inject, Injectable } from '@nestjs/common';
import { CreateLoginDto } from './dto/create-login.dto';
import { UpdateLoginDto } from './dto/update-login.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { encodePwd, sign } from 'src/utils';
@Injectable()
export class LoginService {
  @Inject()
  private prisma: PrismaService;

  async login(createLoginDto: CreateLoginDto) {
    const { userName, password } = createLoginDto;
    const hashedPassword = await encodePwd(password);
    // 检查他是不是admin账号
    const adminUser = await this.prisma.admin.findFirst({
      where: {
        userName,
        password: hashedPassword,
      },
    });
    // 检查他是不是company账号
    const companyUser = await this.prisma.company.findFirst({
      where: {
        userName,
        password: hashedPassword,
      },
    });
    // 检查他是不是CompanyUser  账号
    const companyPersonUser = await this.prisma.companyUser.findFirst({
      where: {
        userName,
        password: hashedPassword,
      },
    });
    // 如果是admin账号 返回role为admin  token为加密后的数据
    if (adminUser) {
      return {
        code: 200,
        message: '登录成功',
        data: {
          role: 'admin',
          token: await sign(adminUser),
        },
      };
    }

    // 如果是companyUser账号 返回role为companyUser  token为加密后的数据
    if (companyUser) {
      return {
        code: 200,
        message: '登录成功',
        data: {
          role: 'companyUser',
          token: await sign(companyUser),
        },
      };
    }
    // 如果是companyPersonUser账号 返回role为companyPersonUser  token为加密后的数据
    if (companyPersonUser) {
      return {
        code: 200,
        message: '登录成功',
        data: {
          role: 'companyPersonUser',
          token: await sign(companyPersonUser),
        },
      };
    }
    if (!adminUser && !companyUser && !companyPersonUser) {
      return {
        code: 400,
        message: '用户名或密码错误',
      };
    }
  }
}
